import { Dispatch } from 'redux';

import * as actions from '../action-type';
import * as UserApi from '@lib/api/user';

import { IUser } from '@lib/types';

export function setUser(user: IUser | null | undefined) {
	return {
		type: actions.SET_USER,
		user
	}
}

export function refresh() {
	return async (dispatch: Dispatch) => {
		const res = await UserApi.Me();
		if (!(res instanceof Error)) {
			dispatch(setUser(res.user));
		}
	}
}

export function logout() {
	return async (dispatch: Dispatch) => {
		const res = await UserApi.Me();
		if (!(res instanceof Error)) {
			dispatch(setUser(res.user));
		}
	}
}